//
//  ViewController.m
//  QiniuTool
//
//  Created by 周渊 on 14/12/31.
//  Copyright (c) 2014年 周渊. All rights reserved.
//

#import "ViewController.h"
#import "QiniuSDK.h"
#import "Tool.h"
#import "AFNetworking.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
}



#pragma mark - DragDropViewDelegate
-(void)dragDropViewFileList:(NSArray *)fileList{
    if(!fileList || [fileList count] <= 0){
     [Tool showMsg:@"错误提示" message:@"请选择一个文件"];
        return;
    };
    [self getTokenAndUpload:[fileList objectAtIndex:0]];
    self.fileInput.stringValue = [fileList objectAtIndex:0];
}

-(void)getTokenAndUpload:(NSString *)file {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型
    
    [manager POST:@"http://qiniu.wuyinchun.cn/token.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *token = [responseObject objectForKey:@"token"];
        [self uploadFile:file andToken:token];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}

-(void)getTokenAndUploadData:(NSData *)data {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//设置相应内容类型
    
    [manager POST:@"http://qiniu.wuyinchun.cn/token.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *token = [responseObject objectForKey:@"token"];
        [self uploadData:data andToken:token];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}


-(void) uploadFile:(NSString *)filePath andToken:(NSString *)token{
    [self.progress setHidden:NO];
    
    QNUploadOption *option = [[QNUploadOption alloc ]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        self.progress.doubleValue = percent*100;
    } params:nil checkCrc:YES cancellationSignal:nil];
    
    
    
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    NSString *fileName = [self getNewFileName:filePath];
    NSLog(@"%@",fileName);
    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
    [upManager putFile:fileUrl.path key:fileName token:token
              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                  if(info.isOK){
                     self.resultInput.stringValue = [NSString stringWithFormat:@"%@/%@",@"http://qnupload.wuyinchun.cn",fileName];
                    [self.progress setHidden:YES];
                  } else {
                      [Tool showMsg:@"上传失败" message:info.error.userInfo.description];
                  }
                  
              } option:option];

}

-(void) uploadData:(NSData *)data  andToken:(NSString *)token{
    [self.progress setHidden:NO];
    
    QNUploadOption *option = [[QNUploadOption alloc ]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        self.progress.doubleValue = percent*100;
    } params:nil checkCrc:YES cancellationSignal:nil];
    
    NSString *fileName = [self getNewFileName:@"aaaaa.png"];
    
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    [upManager putData:data key:fileName token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if(info.isOK){
            self.resultInput.stringValue = [NSString stringWithFormat:@"%@/%@",@"http://qnupload.wuyinchun.cn",fileName];
            [self.progress setHidden:YES];
        } else {
            [Tool showMsg:@"上传失败" message:info.error.userInfo.description];
        }
    } option:option];
    
}


/**
 *   获取新得文件名称
 *
 *  @param filePath <#filePath description#>
 *
 *  @return <#return value description#>
 */
-(NSString *)getNewFileName:(NSString *) filePath{
    NSString *fileEx =  [filePath pathExtension];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000000;
    NSString *timeString = [NSString stringWithFormat:@"%ld", (long)a];//转为字符型
    return [NSString stringWithFormat:@"%@.%@",timeString,fileEx];
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

- (IBAction)choseFile:(id)sender {
    
    NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    
    [openDlg setCanChooseFiles:TRUE]; //确定可以选择文件
    [openDlg setCanChooseDirectories:FALSE]; //可以浏览目录
    [openDlg setAllowsMultipleSelection:FALSE]; //不可以多选
    [openDlg setAllowsOtherFileTypes:FALSE]; //不可以选择其他格式类型的文件
    //    [openDlg setAllowedFileTypes:[NSArray arrayWithObject:@"png"]]; //可以选择.png后缀的文件
    if ([openDlg runModal] == NSModalResponseOK) {  //如果用户点OK
        [self.fileInput setStringValue:[[openDlg URL] path]]; //获得选择的文件路径，这个地方我也GG很久，后来试出来这个。
        [self getTokenAndUpload:[[openDlg URL] path]];
        
    }
}
- (IBAction)copyUrl:(id)sender {
    NSPasteboard *pb = [NSPasteboard generalPasteboard];
    [self writeToPasteboard:pb withString:[self.resultInput stringValue]];
}

- (IBAction)uploadCopy:(id)sender {
    NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
      //判断是否包含RTF
    if ([pasteboard canReadItemWithDataConformingToTypes:@[NSPasteboardTypeTIFF]])
    {
        //获取RTF代表的文本
        NSData *imageData = [pasteboard dataForType:NSPasteboardTypeTIFF];
        [self getTokenAndUploadData:imageData];
    }
}

- (void)writeToPasteboard:(NSPasteboard *)pb withString:string{
    [pb declareTypes:[NSArray arrayWithObject:NSStringPboardType]
               owner:self];
    [pb setString:string forType:NSStringPboardType];
}
@end
